<?php
/**
 * Created by PhpStorm.
 * User: jiangjunxian
 * Date: 2016/12/2
 * Time: 17:57
 */

namespace app\modules\admin\models\search;

use Yii;
use yii\base\Model;
use yii\data\ArrayDataProvider;
use yii\rbac\Item;

class AuthItemSearch extends Model
{
    public $name;
    public $description;
    public $type;
    public $ruleName;

    public function rules()
    {
        return [
            [['name', 'ruleName', 'description'], 'safe'],
            [['type'], 'integer'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'name' => '名称',
            'description' => '描述',
            'ruleName' => '规则名称',
        ];
    }


    public function search($params) {
        $mgr = Yii::$app->authManager;
        $items = [];
        if ($this->type == Item::TYPE_ROLE) {
            $items = $mgr->getRoles();
        } else {
            $items = array_filter($mgr->getPermissions(), function($item) {
                return $this->type === Item::TYPE_PERMISSION xor strncmp($item->name, '/', 1) === 0;
            });
        }
        $this->load($params);
        if($this->validate()) {
            $search = strtolower(trim($this->name));
            $desc = strtolower(trim($this->description));
            $ruleName = $this->ruleName;
            foreach ($items as $name => $item) {
                $boolean = (empty($search) || strpos(strtolower($item->name), $search) !== false) &&
                    (empty($desc) || strpos(strtolower($item->description), $desc) !== false) &&
                    (empty($ruleName) || strpos(strtolower($item->ruleName), $ruleName) !== false);
                if(!$boolean) unset($items[$name]);
            }
        }
        return new ArrayDataProvider([
            'allModels' => $items,
        ]);
    }

}